#import "BaseWebViewViewController.h"
#import <AFNetworking.h>
#import "LMWebProgressLayer.h"

@interface BaseWebViewViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>

@property(nonatomic,strong) WKWebViewConfiguration *wkWebConfig;

///监听动作回调字典
@property (nonatomic, strong) NSMutableDictionary *nameDic;

@property (nonatomic, strong) LMWebProgressLayer *progressLayer;

@end

@implementation BaseWebViewViewController

#pragma mark - lives
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar.layer addSublayer:self.progressLayer];
    
    self.title = self.titleStr;
    
    [MBProgressHUD showHUDAddedTo:KKEYWINDOW animated:YES];
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self CloseSilderBack];
}

- (void)dealloc {
    [self.progressLayer closeTimer];
    [self.progressLayer removeFromSuperlayer];
    self.progressLayer = nil;
}

#pragma mark - public
- (void)initWebViewWithURLStr:(NSString *)urlStr{
    [self initWebViewWithURLStr:urlStr superView:self.view];
}

- (void)initWebViewWithURLStr:(NSString *)urlStr superView:(UIView *)superView{
    [superView addSubview:self.wkWeb];
    
    [self.wkWeb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
    
    if ([urlStr containsString:@"http"] || [urlStr containsString:@"https"]) {
        [self.wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    }else{
        NSString *filePath = [[NSBundle mainBundle] pathForResource:urlStr ofType:nil];
        NSURL *url = [NSURL fileURLWithPath:filePath];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.wkWeb loadRequest:request];
    }
}

- (void)addActionWithName:(NSString *)name
                 callBack:(void (^)(NSString * _Nonnull))callback{
    [self.wkWeb.configuration.userContentController addScriptMessageHandler:[[WeakWKScriptMessageHandler alloc] initWithDelegate:self] name:name];
    [self.nameDic setValue:callback forKey:name];
}

#pragma mark - WKDelegate
//实现js注入方法的协议方法
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    WKActionCallBack callback = self.nameDic[message.name];
    callback(message);
    
}

/// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self.progressLayer startLoad];
}


//加载完毕
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    
    [self.progressLayer finishedLoad];
    [MBProgressHUD hideHUDForView:KKEYWINDOW animated:YES];
    
}


/// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [_progressLayer finishedLoad];
    [MBProgressHUD hideHUDForView:KKEYWINDOW animated:YES];
}

//! WKWeView在每次加载请求前会调用此方法来确认是否进行请求跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    decisionHandler(WKNavigationActionPolicyAllow);
}


#pragma mark - lazy
- (WKWebView *)wkWeb{
    if (!_wkWeb) {
        _wkWeb = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.wkWebConfig];
        _wkWeb.UIDelegate = self;
        _wkWeb.navigationDelegate = self;
        _wkWeb.scrollView.showsHorizontalScrollIndicator = NO;
        _wkWeb.scrollView.showsVerticalScrollIndicator = NO;
    }
    return _wkWeb;
}

-(WKWebViewConfiguration *)wkWebConfig {
    if (!_wkWebConfig) {
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        _wkWebConfig = [[WKWebViewConfiguration alloc] init];
        _wkWebConfig.userContentController = wkUController;
    }
    return _wkWebConfig;
}

- (NSMutableDictionary *)nameDic{
    if (!_nameDic) {
        _nameDic = NSMutableDictionary.dictionary;
    }
    return _nameDic;
}

- (LMWebProgressLayer *)progressLayer{
    if (!_progressLayer) {
        _progressLayer = [LMWebProgressLayer new];
        _progressLayer.frame = CGRectMake(0, 42, SCREEN_WIDTH, 2);
    }
    return _progressLayer;
}

@end


@implementation WeakWKScriptMessageHandler


- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)delegate{
    self = [super init];
    if (self) {
        _delegate = delegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([self.delegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.delegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}


@end
